<template>
  <div class="login-container">
    <el-card class="login-card">
      <h2 class="system-title">🚀 {{ $t("title") }}</h2>
      <el-form :model="form" @submit.prevent="submit" class="login-form">
        <el-form-item prop="username">
          <el-input v-model="form.username" :placeholder="$t('username')">
            <template #prefix>
              <el-icon>
                <User />
              </el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item prop="password">
          <el-input v-model="form.password" type="password" :placeholder="$t('password')">
            <template #prefix>
              <el-icon>
                <Lock />
              </el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item v-if="showCaptcha" class="captcha-container">
          <el-input v-model="form.captcha" :placeholder="$t('captcha')" class="captcha-input" />
          <img :src="captchaSrc" class="captcha-img" @click="refreshCaptcha" />
        </el-form-item>

        <el-form-item v-if="showSms" class="sms-container">
          <el-input v-model="form.smsCode" :placeholder="$t('smsCode')" class="sms-input" />
          <el-button :disabled="countdown > 0" @click="sendSms">{{ countdown > 0 ? `${countdown}s` : $t('sendSms')
            }}</el-button>
        </el-form-item>

        <el-form-item v-if="showMfa">
          <el-input v-model="form.mfaCode" :placeholder="$t('mfaCode')">
            <template #prefix>
              <el-icon>
                <Key />
              </el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-button type="primary" native-type="submit" class="login-button" :loading="loading">{{ $t("login.login") }}</el-button>
        
        <!-- 添加第三方登录区域 -->
        <div class="third-party-login">
          <div class="divider">
            <span>{{ $t('login.orLoginWith') || '或使用以下方式登录' }}</span>
          </div>
          <div class="oauth-buttons">
            <el-button @click="handleGoogleLogin" class="google-btn">
              <img src="@/assets/google-icon.svg" alt="Google" class="oauth-icon" />
              Google
            </el-button>
          </div>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { User, Lock, Key } from '@element-plus/icons-vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { useI18n } from 'vue-i18n';
import { useAuthStore } from '@/stores/auth';

const { t } = useI18n();
const router = useRouter();
const authStore = useAuthStore();

const showCaptcha = ref(false);
const showSms = ref(false);
const showMfa = ref(false);
const captchaSrc = ref('');
const countdown = ref(0);
const loading = ref(false);
const form = ref({
  username: 'root', 
  password: '123456', 
  captcha: '', 
  smsCode: '', 
  mfaCode: '',
  captcha_id: '',
  // 移除这些初始值，完全依赖后端配置
  // use_captcha: showCaptcha.value,
  // use_sms: showSms.value,
  // use_mfa: showMfa.value
});

const GetLoginConfig = async () => {
  let resp_data = await http.get("/auth/login_config")
  console.log(resp_data)
  
  // 统一处理所有配置
  form.value.use_captcha = resp_data.captcha_enabled
  form.value.use_sms = resp_data.sms_enabled
  form.value.use_mfa = resp_data.mfa_enabled
  
  // 更新显示状态
  showCaptcha.value = resp_data.captcha_enabled
  showSms.value = resp_data.sms_enabled
  showMfa.value = resp_data.mfa_enabled
  
  // 如果需要验证码，立即获取
  if (resp_data.captcha_enabled) {
    form.value.captcha_id = resp_data.captcha_id
    await refreshCaptcha()
  }
}

onMounted(() => {
  GetLoginConfig()
  
  // 检查URL中是否有OAuth回调参数
  const urlParams = new URLSearchParams(window.location.search);
  const token = urlParams.get('token');
  const error = urlParams.get('error');
  
  if (token) {
    // 处理成功的OAuth登录
    handleOAuthCallback(token);
  } else if (error) {
    // 处理OAuth登录错误
    ElMessage.error(decodeURIComponent(error) || '第三方登录失败');
  }
});

// 处理OAuth回调
const handleOAuthCallback = async (token) => {
  try {
    // 使用token登录
    const success = await authStore.loginWithToken(token);
    if (success) {
      ElMessage.success(t('login.success') || '登录成功');
      router.push('/');
    }
  } catch (error) {
    console.error('OAuth登录处理错误:', error);
    ElMessage.error('登录处理失败');
  }
};

// Google登录处理函数
const handleGoogleLogin = () => {
  // 重定向到后端的Google OAuth授权URL
  window.location.href = 'http://localhost:8000/api/auth/google/login';
};

const submit = async () => {
  // 根据login_config中的配置，决定是否需要验证码、短信验证码、MFA
  if (showCaptcha.value && !form.value.captcha) {
    ElMessage.warning( '图片验证码不能为空');
    return;
  }
  if (showSms.value && !form.value.smsCode) {
    ElMessage.warning( '短信验证码不能为空');
    return;
  }
  if (showMfa.value && !form.value.mfaCode) {
    ElMessage.warning( 'mfaCode不能为空');
    return;
  }
  if (!form.value.username || !form.value.password) {
    ElMessage.warning( '用户名和密码不能为空');
    return;
  }
  
  loading.value = true;
  try {
    // 将表单数据转换为后端需要的格式
    const loginData = {
      username: form.value.username,
      password: form.value.password,
      use_captcha: form.value.use_captcha,
      use_sms: form.value.use_sms,
      use_mfa: form.value.use_mfa,
      captcha_id: form.value.captcha_id ? form.value.captcha_id : null
    };
    console.log(`配置开关:验证码:${form.value.use_captcha},短信验证码:${form.value.use_sms},MFA:${form.value.use_mfa}`);
    
    // 可选字段仅在有值时添加
    if (form.value.captcha) loginData.captcha = form.value.captcha;
    if (form.value.smsCode) loginData.sms_code = form.value.smsCode;
    if (form.value.mfaCode) loginData.mfa_code = form.value.mfaCode;
    
    console.log('尝试登录:', loginData);
    
    const success = await authStore.login(loginData);
    console.log(`登录结果: ${success ? '成功' : '失败'}`);
    
    if (success) {
      ElMessage.success(t('login.success') || '登录成功');
      router.push('/');
    } else {
      console.log('登录失败，停留在登录页面');
    }
  } catch (error) {
    console.error('登录过程发生错误:', error);
  } finally {
    loading.value = false;
  }
};

import http from "@/utils/http"

const refreshCaptcha = async() => {
  let resp_data = await http.get("/auth/captcha")
  console.log(resp_data)
  let { captcha_image, captcha_id } = resp_data
  captchaSrc.value = captcha_image; // 模拟验证码刷新
  form.value.captcha_id = captcha_id;
};

const sendSms = () => {
  if (countdown.value > 0) return;
  countdown.value = 60;
  const timer = setInterval(() => {
    countdown.value--;
    if (countdown.value === 0) clearInterval(timer);
  }, 1000);
};
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f5f5f5;
}

.login-card {
  width: 380px;
  padding: 20px;
  text-align: center;
}

.system-title {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 15px;
  color: #333;
}

.login-form {
  display: flex;
  flex-direction: column;
}

.captcha-container,
.sms-container {
  display: flex;
  align-items: center;
}

.captcha-input {
  flex: 1;
  margin-right: 10px;
}

.captcha-img {
  width: 100px;
  height: 38px;
  cursor: pointer;
}

.sms-input {
  flex: 1;
  margin-right: 10px;
}

.login-button {
  width: 100%;
  margin-top: 10px;
}

/* 第三方登录样式 */
.third-party-login {
  margin-top: 20px;
  width: 100%;
}

.divider {
  display: flex;
  align-items: center;
  margin: 15px 0;
  color: #909399;
  font-size: 14px;
}

.divider::before,
.divider::after {
  content: '';
  flex: 1;
  height: 1px;
  background-color: #dcdfe6;
}

.divider span {
  padding: 0 10px;
}

.oauth-buttons {
  display: flex;
  justify-content: center;
  margin-top: 10px;
}

.google-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  background-color: #fff;
  border: 1px solid #dcdfe6;
  color: #606266;
  width: 100%;
}

.oauth-icon {
  width: 18px;
  height: 18px;
}
</style>
